package com.miplus.ccrm.core.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class XSkyConfig {
    @Value("${xsky.aws.akey}")
    private String aws_akey;

    @Value("${xsky.aws.skey}")
    private String aws_skey;

    @Value("${xsky.aws.endpoint}")
    private String aws_endpoint;

    public AmazonS3 initClient(String endpoint,String akey,String skey)
    {
        AmazonS3 s3client = null;
        // 设置连接时的参数
        ClientConfiguration config = new ClientConfiguration();
        // 设置连接方式为HTTP，可选参数为HTTP和HTTPS
        config.setProtocol(Protocol.HTTP);
        // config.setProtocol(Protocol.HTTPS);
        // 设置网络访问超时时间
        config.setConnectionTimeout(30000);
        config.setUseExpectContinue(true);
        // 获取访问凭证
        AWSCredentials credentials = null;
        credentials = new BasicAWSCredentials(akey, skey);
        // 设置Endpoint
        AwsClientBuilder.EndpointConfiguration end_point = null;
        end_point = new AwsClientBuilder.EndpointConfiguration(endpoint, "");
        // 创建连接
        s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(config).withEndpointConfiguration(end_point).withPathStyleAccessEnabled(true)
                .build();
        return s3client;
    }

    @Bean
    public AmazonS3 awsService() {
        log.info("XSkyConfig.Init:{}",aws_endpoint);
        return initClient(aws_endpoint,aws_akey,aws_skey);
    }
}
